<template>
  <div style="padding: 20px;">
    <div class="filter-container">
      <el-button class="filter-item" type="success" icon="el-icon-folder-add" size="medium" @click="addHandle(tableData.length - 1)">新增步骤</el-button>
      <el-button class="filter-item" style="margin-left: 3px;" type="primary" size="medium" icon="el-icon-edit" @click="saveAllHandle">保存全部</el-button>
      <el-button class="filter-item" style="margin-left: 3px;" icon="el-icon-refresh" size="medium" @click="refreshHandle">刷新步骤</el-button>
      <el-button class="filter-item" style="margin-left: 3px;" icon="el-icon-refresh" size="medium" @click="refreshElements">刷新元素和片段</el-button>
      <el-button class="filter-item" style="margin-left: 3px;" type="danger" icon="el-icon-back" size="medium" @click="returnHandle">返回</el-button>
    </div>
    <div>
      <el-table ref="stepTable" v-loading="listLoading" height="650" border row-key="id" :data="tableData" :row-class-name="tableRowClassName" style="width: 100%">
        <el-table-column prop="seq_num" align="center" label="排序" min-width="60" />
        <el-table-column prop="step_name" align="center" label="步骤名称" min-width="140">
          <template slot-scope="{ row }">
            <el-input v-model="row.step_name" class="edit-input" @change="row.updated = true" />
          </template>
        </el-table-column>

        <el-table-column prop="type" align="center" label="步骤类型" min-width="130">
          <template slot-scope="{ row }">
            <el-select v-model="row.type" class="filter-item" placeholder="请选择" @change="handleChangeStepType(row)">
              <el-option v-for="item in stepType" :key="item" :label="item" :value="item" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="snippet_id" align="center" label="用例片段" min-width="140">
          <template slot-scope="{ row }">
            <el-select v-model="row.snippet_id" clearable class="filter-item" placeholder="请选择" @change="snippetChange(row)">
              <el-option v-for="item in snippets" :key="item.id" :label="item.case_title" :value="item.id" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="keyword_id" align="center" label="关键字" min-width="140">
          <template slot-scope="{ row }">
            <el-select v-model="row.keyword_id" clearable class="filter-item" placeholder="请选择关键字" @change="keywordChange(row)">
              <el-option v-for="item in keyword[row.type]" :key="item.id" :label="item.cn_name" :value="item.id" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="element_id" align="center" label="元素对象" min-width="190">
          <template slot-scope="{ row }">
            <el-cascader
              v-model="row.element_id"
              placeholder="请输入搜索关键字"
              :options="elements"
              :props="{ expandTrigger: 'hover', value: 'id', label: 'node_name' }"
              style="width:100%;"
              :show-all-levels="false"
              filterable
              :clearable="true"
              @change="elementChange(row)"
            >
              <template slot-scope="{ node, data }">
                <span
                  v-if="data.node_level === 2"
                  title="在此页面添加新的元素"
                  class="add-page-ele-icon"
                  @click="openEditPageElementDialog(data)"
                >
                  <i class="el-icon-circle-plus" />
                </span>
                <span
                  v-if="data.type === 'web'"
                  title="修改此元素对象"
                  class="add-page-ele-icon"
                  @click="openEditPageElementDialog(data)"
                >
                  <i class="el-icon-edit" />
                </span>
                <span> <i  v-if="data.node_level === 1" class="el-icon-circle-plus add-page-ele-icon"  @click="addPageElementDialog(data)"/>
                  {{ data.node_name }}
                </span>
              </template>
            </el-cascader>
          </template>
        </el-table-column>

        <el-table-column prop="code" align="center" label="code" min-width="130">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="openCodeHandle(row)">代码编辑</el-button>
          </template>
        </el-table-column>

        <el-table-column prop="control_id" align="center" label="逻辑控制" min-width="120">
          <template slot-scope="{ row }">
            <el-select v-model="row.control_id" clearable class="filter-item" placeholder="请选择" @change="row.updated = true">
              <el-option v-for="item in stepControl" :key="item.id" :label="item.cn_name" :value="item.id" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="default_data" align="center" label="测试数据" :show-overflow-tooltip="true" min-width="160">
          <template slot-scope="{ row }">
            <template v-if="row.default_data === '{}'">
              <el-button type="text" size="small" circle @click="handleSettingData(row, 'default_data')">
                配置
              </el-button>
            </template>
            <span v-else class="setting-data" @click="handleSettingData(row, 'default_data')">{{ parseJsonToParams(row.default_data) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="export_data" align="center" label="输出数据" :show-overflow-tooltip="true" min-width="160">
          <template slot-scope="{ row }">
            <template v-if="row.export_data === '{}'">
              <el-button type="text" size="small" circle @click="handleSettingData(row, 'export_data')">
                配置
              </el-button>
            </template>
            <span v-else class="setting-data" @click="handleSettingData(row, 'export_data')">{{ parseJsonToParams(row.export_data) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="expected_result" align="center" label="预期结果" :show-overflow-tooltip="true" min-width="160">
          <template slot-scope="{ row }">
            <template v-if="row.expected_result === '{}'">
              <el-button type="text" size="small" circle @click="handleSettingData(row, 'expected_result')">
                配置
              </el-button>
            </template>
            <span v-else class="setting-data" @click="handleSettingData(row, 'expected_result')">{{ parseJsonToParams(row.expected_result) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="mark" align="center" label="备注" min-width="90">
          <template slot-scope="{ row }">
            <el-input v-model="row.mark" class="edit-input" size="small" @change="row.updated = true" />
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="140">
          <template slot-scope="scope">
            <!-- <el-button type="text" size="small" @click="addHandle(scope.$index)">增加</el-button> -->
            <el-button type="text" size="small" @click="copyHandle(scope.row, scope.$index)">复制</el-button>
            <el-button type="text" size="small" @click="deleteHandle(scope.row, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="'编辑步骤数据-' + currentStep.step_name" :visible.sync="settingDataDialogVisible" width="36%" :close-on-click-modal="false" :center="true">
      <stepData :data-type="dataType" :step-data="stepData" :step-data-params="stepDataParams" @closeDataSetting="closeDataSetting" />
    </el-dialog>

    <el-dialog :title="editPageElement.temp.id !== undefined ? '修改元素对象' : '新增元素对象'" :visible.sync="editPageElement.visible">
      <el-form ref="pageElementDataForm" :rules="editPageElement.rules" :model="editPageElement.temp" label-position="left" label-width="140px" style="margin-left:20px;">
        <el-form-item label="元素名称" prop="element_name">
          <el-input v-model="editPageElement.temp.element_name" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="元素类型" prop="type">
          <el-select v-model="editPageElement.temp.type" class="filter-item" placeholder="请选择">
            <el-option v-for="item in elementType" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="定位类型" prop="location_by_id">
          <el-select v-model="editPageElement.temp.location_by_id" class="filter-item" placeholder="请选择">
            <el-option v-for="item in locationBy" :key="item.cn_name" :label="item.cn_name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="定位值" prop="by_value">
          <el-input v-model="editPageElement.temp.by_value" />
        </el-form-item>
        <el-form-item label="所属frame/iframe" prop="frame_id">
          <el-cascader
            v-model="editPageElement.temp.frame_id"
            placeholder="请输入搜索关键字"
            :options="editPageElement.webFrameOptions"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'node_name'}"
            style="width:360px;"
            filterable
            :clearable="true"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editPageElement.temp.mark" :autosize="{ minRows: 4, maxRows: 8}" type="textarea" placeholder="输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="editPageElement.visible = false">
          取消
        </el-button>
        <el-button size="medium" type="primary" @click="editPageElementHandle">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="inCode.title" :visible.sync="inCode.flag">
      <in-coder v-if="reFresh" v-model="inCode.code" language="x-python" :value="inCode.code" />
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="inCode.flag = false">
          取消
        </el-button>
        <el-button size="medium" type="primary" @click="editCoderHandle">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSteps, stepEdit, delStep, caseList, sortStep, stepParams } from '@/api/caseStep'
import { addNode, elementEdit } from '@/api/element'
import { batchHandle, parseTreeData } from '@/utils/commonUtil.js'
import { parseJsonToParams, parseJsonToArray, CompareJsonObj, isArray } from '@/utils/jsonUtil.js'
import { elementList, getElementPageList } from '@/api/element'
import Sortable from 'sortablejs'
import stepData from './stepData.vue'
import InCoder from '@/components/CodeMirror/index'

export default {
  name: 'CaseStep',
  components: {
    stepData,
    InCoder
  },
  props: {
    caseId: {
      type: String,
      default: ''
    },
    caseTitle: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tableData: [],
      newSaveData: [],
      sortNums: [],
      delArray: [], // 页面删除元素
      elementList: [], // 原始数组 页面元素
      elements: [], // 页面元素，已经转换过tree模式
      snippets: [], // 用例片段
      listLoading: true,
      globalGoBack: false,
      tempRoute: {},
      dataType: '',
      settingDataDialogVisible: false,
      stepDataParams: {},
      currentStep: {},
      stepData: {},
      editPageElement: {
        visible: false,
        temp: {
          id: undefined,
          element_name: '',
          type: this.$store.state.user.dictConfig.elementType[0],
          location_by_id: 7,
          by_value: '',
          frame_id: undefined,
          mark: '',
          frame_name: '',
          page_id: this.elementNode === undefined ? '' : this.elementNode.id
        },
        rules: {
          element_name: [{ required: true, message: '请输入元素名称', trigger: 'change' }],
          type: [{ required: true, message: '请选择元素类型', trigger: 'change' }],
          location_by_id: [{ required: true, message: '请选择定位类型', trigger: 'change' }],
          by_value: [{ required: true, message: '请输入定位值', trigger: 'change' }]
        },
        webFrameOptions: []
      },
      inCode: {
        flag: false,
        title: 'Python代码编辑',
        code: '',
        row: {}
      },
      reFresh: false
    }
  },
  computed: {
    stepType() {
      return this.$store.state.user.dictConfig.stepType
    },
    stepControl() {
      return this.$store.state.user.dictConfig.stepControl
    },
    keyword() {
      return this.$store.state.user.dictConfig.keyword
    },
    locationBy() {
      return this.$store.state.user.dictConfig.locationBy
    },
    elementType() {
      return this.$store.state.user.dictConfig.elementType
    }
  },
  watch: {
    '$route'() {
      // 此处写router变化时，想要初始化或者是执行的方法......
      this.delArray = []
      this.getData()
    }
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route)

    this.setTagsViewTitle()
    this.setPageTitle()

    this.getData()
    this.refreshElements()
  },
  mounted() {
    this.$nextTick(() => {
      this.setSort()
    })
  },
  methods: {
    // 获取webFrame
    async getElementWebFrame() {
      let webFrames = []
      await elementList({ type: 'web_frame' }).then(response => {
        webFrames = response.data
      })
      if (webFrames.length > 0) {
        getElementPageList().then(response => {
          const data = response.data
          this.editPageElement.webFrameOptions = parseTreeData(data.filter(item => item.node_level === 0), data, (item, node) => item.parent_node_id === node.id
            , item => {
              if (item.node_level === 2) {
                item.children = webFrames.filter(frame => {
                  if (frame.page_id === item.id) {
                    frame.node_name = frame.element_name
                    return true
                  }
                  return false
                })
              }
              if (item.children === undefined || item.children.length === 0) {
                item.disabled = true
              }
            }, true
          )
        })
      }
    },
    // 给变更过的加上背景色
    tableRowClassName({ row, rowIndex }) {
      if (row.updated === true) {
        return 'warning-row'
      }
      return ''
    },
    // 设置标签页名称
    setTagsViewTitle() {
      const title = '用例步骤'
      const route = Object.assign({}, this.tempRoute, { title: `${title} - ${this.caseTitle}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    // 设置页面标题
    setPageTitle() {
      const title = '用例步骤'
      document.title = `${title} - ${this.caseTitle}`
    },
    // 获取数据
    async getData() {
      this.listLoading = true
      await listSteps({ case_id: this.caseId }).then(response => {
        response.data.forEach(item => {
          item.updated = false
          // TODO 后台接口原因，防止显示异常
          if (item.type === 'snippet') {
            item.keyword_id = undefined
          }
        })
        this.tableData = response.data
      })
      this.listLoading = false
    },
    // 配置排序插件
    setSort() {
      const el = this.$refs.stepTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.tableData.splice(evt.oldIndex, 1)[0]
          this.tableData.splice(evt.newIndex, 0, targetRow)
          this.resetStepSort()
          sortStep(this.sortNums)
        }
      })
    },
    // 新增页面节点
    addPageElementDialog(data) {
      this.$prompt('请输入新增页面名称', '新增页面', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '新页面',
        inputPattern: /.{3,}/,
        inputErrorMessage: '请至少输入三个字符'
      }).then(({ value }) => {
        addNode({
          node_level: data.node_level + 1,
          node_name: value,
          parent_node_id: data.id
        }).then(response => {
          this.getElements()
          this.$message.success('新增页面成功')
        })
      }).catch(() => {})
    },
    // 打开添加指定页面的元素对象或者修改元素那个
    openEditPageElementDialog(data) {
      this.getElementWebFrame()
      this.editPageElement.visible = true
      this.$nextTick(() => {
        this.$refs['pageElementDataForm'].resetFields()

        // 新增元素
        if (data.node_level === 2) {
          this.editPageElement.temp.id = undefined
          this.editPageElement.temp.page_id = data.id
        }
        // 修改元素
        if (data.type === 'web') {
          const elements = this.elementList.filter(function(item) {
            return item.id === data.id
          })
          if (elements.length > 0) {
            this.editPageElement.temp = { ...elements[0] }
          }
        }
      })
    },
    // 新增或者修改元素对象
    editPageElementHandle() {
      if (this.editPageElement.temp.frame_id && this.editPageElement.temp.frame_id.length > 0) {
        this.editPageElement.temp.frame_id = this.editPageElement.temp.frame_id[this.editPageElement.temp.frame_id.length - 1]
      }
      this.$refs['pageElementDataForm'].validate((validate) => {
        if (validate) {
          elementEdit(this.editPageElement.temp).then(() => {
            this.editPageElement.visible = false
            this.getElements()
            this.$message.success(this.editPageElement.temp.id ? '修改成功' : '新增成功')
          })
        }
      })
    },
    // 保存全部
    saveAllHandle() {
      const self = this
      if (!this.checkDataUpdated() && this.delArray.length === 0) {
        this.$message.info('无任何改动')
        return
      }
      batchHandle({
        vm: this, // vue实例
        vmNotify: true,
        opName: '操作', // 操作命令
        data: this.newSaveData, // 数据
        delData: this.delArray, // 删除数据
        opHandle: function(val, resolve, reject) {
          const newVal = Object.assign({}, val)
          if (newVal.keyword_id === undefined) {
            // TODO 因为后台问题，随便设置一个keyword_id， 否则报错
            newVal.keyword_id = 1
          }
          if (newVal.element_id instanceof Array) {
            newVal.element_id = newVal.element_id[newVal.element_id.length - 1]
          }
          stepEdit(newVal)
            .then(response => {
              val.updated = false
              resolve()
            })
            .catch(() => {
              reject()
            })
        },
        delHandle: function(val, resolve, reject) {
          const newVal = Object.assign({}, { id: val.id })
          delStep(newVal)
            .then(response => {
              resolve()
            }).catch(() => {
              reject()
            })
        },
        beginCallback() {
          self.listLoading = true
        },
        finishCallback(successCount, failCount) {
          // 防止一些新增的步骤没有ID 导致排序不成功
          self.getData()
          self.delArray = []
          self.listLoading = false
          if (self.globalGoBack) {
            self.routeGoBack()
          }
        }, // 完成之后的回调
        intervalTime: 300 // 检测时间间隔
      })
    },
    // 刷新列表
    refreshHandle() {
      if (!this.checkDataUpdated()) {
        this.getData()
        this.$message.success('刷新成功')
        return
      }

      // 提示是否需要保存变动
      this.$confirm('该用例步骤发生了变动，你是否需要保存?<br>(取消操作请点击右上方X)', '提示', {
        dangerouslyUseHTMLString: true,
        distinguishCancelAndClose: true,
        confirmButtonText: '保存修改',
        cancelButtonText: '放弃修改并刷新',
        type: 'warning'
      }).then(() => {
        this.saveAllHandle()
      }).catch(action => {
        if (action === 'close') {
          return
        }
        this.getData()
        // 重置删除列表
        this.delArray = []
        this.$message.success('刷新成功')
      })
    },
    // 新增一行
    addHandle(index) {
      this.tableData.splice(index + 1, 0, {
        case_id: this.caseId,
        control_id: '',
        default_data: '{}',
        element_id: '',
        expected_result: '{}',
        export_data: '{}',
        id: undefined,
        keyword_id: undefined,
        mark: '',
        seq_num: this.tableData.length + 1,
        snippet_id: '',
        snippet_setting: '{"executeCount":"1","exitCondition":"成功","errorStillRun":"false"}',
        step_name: '测试步骤' + new Date().getTime(),
        type: this.stepType[0],
        updated: true
      })
      this.resetStepSort()
    },
    // 复制
    copyHandle(row, index) {
      const newObj = Object.assign({}, row)
      newObj.id = undefined
      newObj.updated = true
      this.tableData.splice(index + 1, 0, newObj)
      this.resetStepSort()
    },
    // 删除一行数据
    deleteHandle(row, index) {
      this.$confirm('是否要删除用例步骤 【' + row.step_name + '】?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.id === undefined) {
          this.tableData.splice(index, 1)
          this.resetStepSort()
        } else {
          this.tableData.splice(index, 1)
          this.delStepArrayHandle(row)
        }
      })
    },
    // 关闭页面
    returnHandle() {
      if (this.checkDataUpdated() || this.delArray.length > 0) {
        this.$confirm('该用例步骤发生了变动，你是否需要保存?<br>(取消操作请点击右上方X)', '提示', {
          dangerouslyUseHTMLString: true,
          distinguishCancelAndClose: true,
          confirmButtonText: '保存并返回',
          cancelButtonText: '放弃修改并返回',
          type: 'warning'
        }).then(() => {
          this.globalGoBack = true
          this.saveAllHandle()
        }).catch(action => {
          if (action === 'close') {
            return
          }
          this.routeGoBack()
        })
      } else {
        this.routeGoBack()
      }
    },
    // 转换数据json=>key=value
    parseJsonToParams(data) {
      return parseJsonToParams(data)
    },
    // 变更关键字类型
    handleChangeStepType(row) {
      row.keyword_id = undefined
      row.updated = true
    },
    // 获取元素列表
    getElements() {
      elementList({ type: 'web' }).then(response => {
        this.elementList = response.data
        if (this.elementList.length > 0) {
          getElementPageList().then(response => {
            const data = response.data
            this.elements = parseTreeData(
              data.filter(item => item.node_level === 0),
              data,
              (item, node) => item.parent_node_id === node.id,
              item => {
                if (item.node_level === 2) {
                  item.children = this.elementList.filter(frame => {
                    if (frame.page_id === item.id) {
                      frame.node_name = frame.element_name
                      return true
                    }
                    return false
                  })
                }
                if (item.children === undefined || item.children.length === 0) {
                  item.disabled = true
                }
              },
              true
            )
          })
        }
      })
    },
    // 获取用例片段
    getSnippets() {
      caseList({ case_type: 'snippet' }).then(response => {
        this.snippets = response.data
      })
    },
    // 刷新元素和用例片段
    refreshElements() {
      this.getElements()
      this.getSnippets()
    },
    // 重置步骤的排序， 在删除，新增，拖拽的时候触发更新
    resetStepSort() {
      this.sortNums = []
      const self = this
      this.tableData.forEach(function(item, index) {
        item.seq_num = index + 1
        self.sortNums.push(item.id)
      })

      // if (sortNums.length > 0) {
      //   // 后台排序
      //   sortStep(sortNums).then(response => {
      //   // TODO 后台排序成功

      //   }).catch(() => {
      //     // TODO 后台排序不成功需要回退,获取
      //     //this.$refs.stepTable.doLayout()
      //   })
      // }
    },
    // 点击需要后端删除数据时触发
    delStepArrayHandle(row) {
      this.delArray.push(row)
    },

    // 检查数据是否有变更
    checkDataUpdated() {
      this.newSaveData = []
      this.tableData.forEach(item => {
        if (item.updated) {
          this.newSaveData.push(item)
        }
      })

      return this.newSaveData.length > 0
    },
    // 用例片段改变
    snippetChange(row) {
      row.updated = true
      if (row.snippet_id !== undefined) {
        const snippet = this.snippets.filter(item => item.id === row.snippet_id)[0]
        row.step_name = '执行-' + snippet.case_title
      }
    },
    // 元素对象改变
    elementChange(row) {
      row.updated = true
      if (row.type === 'function') {
        return false
      }
      if (row.element_id.length > 0 && row.keyword_id !== undefined) {
        const ele = this.elementList.filter(item => item.id === row.element_id[row.element_id.length - 1])[0]
        const keyObj = this.keyword[row.type].filter(item => item.id === row.keyword_id)[0]
        row.step_name = keyObj.cn_name + '-' + ele.element_name
      }
    },
    // 关键字改变
    keywordChange(row) {
      row.updated = true
      if (row.type === 'function') {
        const keyObj = this.keyword[row.type].filter(item => item.id === row.keyword_id)[0]
        row.step_name = keyObj.cn_name
        return true
      }
      let element_id = row.element_id
      if (isArray(row.element_id) && row.element_id.length > 0) {
        element_id = row.element_id[row.element_id.length - 1]
      }

      if (element_id !== undefined && row.keyword_id !== undefined) {
        const ele = this.elementList.filter(item => item.id === element_id)[0]
        const keyObj = this.keyword[row.type].filter(item => item.id === row.keyword_id)[0]
        row.step_name = keyObj.cn_name + '-' + ele.element_name
      }
    },
    // 配置不同类型的数据
    async handleSettingData(row, dataType) {
      this.listLoading = true
      this.dataType = dataType
      this.stepDataParams = {
        export_data: ['[自定义数据]']
      }
      this.stepData = {
        default_data: parseJsonToArray({
          data: row.default_data,
          insertEmpty: true,
          customData: {
            custom: true
          }
        }),
        export_data: parseJsonToArray({
          data: row.export_data,
          insertEmpty: true,
          customData: {
            custom: true
          }
        }),
        expected_result: parseJsonToArray({
          data: row.expected_result,
          insertEmpty: true,
          customData: {
            custom: true
          }
        })
      }
      this.currentStep = row
      // 从后台获取参数
      await stepParams({
        element_id: row.element_id,
        step_type: row.type,
        keyword_id: row.keyword_id,
        param_type: 'test_data'
      }).then(response => {
        this.stepDataParams.default_data = ['[自定义数据]'].concat(response.data)
      })

      await stepParams({
        element_id: row.element_id,
        step_type: row.type,
        keyword_id: row.keyword_id,
        param_type: 'expect'
      }).then(response => {
        this.stepDataParams.expected_result = ['[自定义数据]'].concat(response.data)
      })
      this.listLoading = false
      this.settingDataDialogVisible = true
    },
    // 关闭数据编辑窗口 处理数据
    closeDataSetting(data) {
      this.settingDataDialogVisible = false
      if (typeof data === 'object') {
        for (const k in data) {
          if (!CompareJsonObj(JSON.parse(this.currentStep[k]), data[k])) {
            this.currentStep[k] = JSON.stringify(data[k])
            this.currentStep.updated = true
          }
        }
      }
    },
    routeGoBack() {
      // 返回也面前重置删除列表
      this.delArray = []
      this.globalGoBack = false
      this.$store.dispatch('tagsView/delVisitedView', this.$route)
      this.$router.go(-1)
    },
    openCodeHandle(row) {
      this.inCode.flag = true
      this.refreshCompent()
      this.inCode.code = row.code
      this.inCode.row = row
    },
    editCoderHandle() {
      const self = this
      this.tableData.forEach(function(item) {
        if (item.id === self.inCode.row.id) {
          if (item.code === self.inCode.code) {
            return false
          }
          item.code = self.inCode.code
          item.updated = true
          return false
        }
      })
      this.reFresh = false
      this.inCode.flag = false
    },
    refreshCompent() {
      // 销毁组件
      this.reFresh = false
      this.$nextTick(() => {
        // 强制刷新
        this.reFresh = true
      })
    }
  },
  // 路由切换在进入的时候，重新修改TagView上的标签名和浏览器标签页名称
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.setTagsViewTitle()
      vm.setPageTitle()
    })
  }
}
</script>

<style scoped>
/deep/ .el-table .warning-row {
  background: oldlace;
}

/deep/ .sortable-ghost {
  opacity: 0.8;
  color: #fff !important;
  background: #42b983 !important;
}

.setting-data {
  cursor: pointer;
}

.add-page-ele-icon {
  margin-right: 5px;
  cursor: pointer;
  font-size: 14px;
}

.add-page-ele-icon :hover {
  color: red;
}
</style>
